package com.cyl.chat.service.impl;


import okhttp3.*;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.cyl.chat.service.BaiduWenxinService;
import java.io.IOException;


@Service("baiduWenxinService")
public class BaiduWenxinServiceImpl implements BaiduWenxinService {

    private static final Logger logger = LoggerFactory.getLogger(BaiduWenxinServiceImpl.class);

    @Value("${baidu.client-id}")
    private String clientId;

    @Value("${baidu.client-secret}")
    private String clientSecret;

    @Value("${baidu.token-url}")
    private String tokenUrl;

    @Value("${baidu.chat-url}")
    private String chatUrl;

    @Value("${baidu.appid}")
    private String appId;

    @Value("${baidu.model}")
    private String model;

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");

    private String accessToken;
    private long tokenExpireTime;

    // 实现 getAccessToken 方法，但在当前需求下此方法用不到，可空实现
    @Override
    public String getAccessToken() throws IOException {
        return null;
    }

    @Override
    public String chat(String message) throws IOException {
//        OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

        // 设置连接超时时间为 30 秒，读取超时时间为 60 秒
        OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
                .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
                .build();

        MediaType mediaType = MediaType.parse("application/json");


        // 动态设置用户输入的消息
        String requestBodyJson = "{\"model\":\"ernie-x1-32k\",\"messages\":[{\"role\":\"user\",\"content\":\"" + message + "\"}],\"web_search\":{\"enable\":false,\"enable_citation\":false,\"enable_trace\":false}}";
        RequestBody body = RequestBody.create(mediaType, requestBodyJson);

        Request request = new Request.Builder()
                .url("https://qianfan.baidubce.com/v2/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer bce-v3/ALTAK-LQA5oYRKtmbXHITO2T6kP/87b0a870216daacc4bb44c088d665cc298b5c5ee")
                .addHeader("appid", "app-twTbB73j")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String reply = response.body().string();
                System.out.println(reply);
                return reply;
            } else {
                System.err.println("请求失败，状态码: " + response.code());
                return null;
            }
        }
    }
}
